#include <QApplication>
#include <QLibraryInfo>
#include <QLocale>
#include <QTranslator>
#include "main-window.h"
#include "meta-types.h"
#include "notifier.h"
#include "section-view-tab-widget.h"
#include "settings.h"
#include "standard-paths.h"
#include "widget-helper.h"
#ifdef TEST_SERVER
#include "test-server/test-server.h"
#endif

MainWindow::MainWindow (QWidget *parent) :
    QMainWindow(parent)
{
    setupTranslations();
    setupChildObjects();
    loadSettings();
}

MainWindow::~MainWindow()
{
}

void MainWindow::setupTranslations()
{
    // load translations from Qt library
    m_qtTranslator = new QTranslator(this);
    if (m_qtTranslator->load("qt_" + QLocale::system().bcp47Name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        qApp->installTranslator(m_qtTranslator);
    else if (m_qtTranslator->load("qt_" + QLocale::system().bcp47Name(), StandardPaths::translationsPath()))
        qApp->installTranslator(m_qtTranslator);
    else
        delete m_qtTranslator;
}

void MainWindow::setupChildObjects()
{
    m_metaTypes = new MetaTypes(this);
    m_notifier = new Notifier(this);
    connect (this, &MainWindow::notifyHint, m_notifier, &Notifier::showHint);
    connect (this, &MainWindow::notifyInformation, m_notifier, &Notifier::showInformation);
    connect (this, &MainWindow::notifyWarning, m_notifier, &Notifier::showWarning);

    m_sectionViewTabWidget = new SectionViewTabWidget(this);
    m_sectionViewTabWidget->setDocumentMode(true);
    m_sectionViewTabWidget->setTabPosition(QTabWidget::South);
    setCentralWidget(m_sectionViewTabWidget);
    connect (m_sectionViewTabWidget, &SectionViewTabWidget::notifyHint, m_notifier, &Notifier::showHint);
    connect (m_sectionViewTabWidget, &SectionViewTabWidget::notifyInformation, m_notifier, &Notifier::showInformation);
    connect (m_sectionViewTabWidget, &SectionViewTabWidget::notifyWarning, m_notifier, &Notifier::showWarning);
}

void MainWindow::loadSettings()
{
    Settings settings;
    settings.beginGroup("MainWindow");
    QByteArray geometry = settings.value("geometry").toByteArray();
    if (geometry.isEmpty())
        WidgetHelper::centerWidgetPosition(this);
    else
        restoreGeometry(geometry);
    settings.endGroup();
}

void MainWindow::saveSettings()
{
    Settings settings;
    settings.beginGroup("MainWindow");
    settings.setValue("geometry", saveGeometry());
}

void MainWindow::closeEvent (QCloseEvent* event)
{
    saveSettings();
    QMainWindow::closeEvent(event);
}
